// 纯效果肉鸽系统 - 无UI干扰，只有游戏增强效果
(function() {
    'use strict';
    
    class RoguelikeEffects {
        constructor() {
            this.active = false;
            this.currentRun = {
                upgrades: [],
                equipment: 0,
                kills: 0
            };
            
            // 血量继承系统
            this.healthPersistence = {
                enabled: true,
                savedHealth: null,
                lastMaxHealth: null,
                monitoring: false
            };
            
            // 静默启动
            setTimeout(() => {
                this.initialize();
            }, 3000);
        }
        
        initialize() {
            try {
                if (!this.checkBasicSystems()) {
                    setTimeout(() => this.initialize(), 2000);
                    return;
                }
                
                this.active = true;
                this.startEffects();
                console.log('🎲 肉鸽效果系统已激活');
                
            } catch (error) {
                console.error('肉鸽效果系统初始化失败:', error);
            }
        }
        
        checkBasicSystems() {
            return window.gameEngine && window.levelManager && window.player;
        }
        
        startEffects() {
            // 立即开始装备掉落
            this.startEquipmentDrops();
            
            // 开始游戏监控
            this.startGameMonitoring();
            
            // 开始属性增强
            this.startAttributeEnhancements();
            
            // 开始血量继承监控
            this.startHealthPersistence();
        }
        
        startEquipmentDrops() {
            // 游戏开始后立即掉落第一个装备
            setTimeout(() => {
                this.dropEquipment();
            }, 5000);
            
            // 之后每20秒掉落一次
            setInterval(() => {
                if (this.isGameActive()) {
                    this.dropEquipment();
                }
            }, 20000);
        }
        
        dropEquipment() {
            try {
                if (!window.gameEngine || !window.gameEngine.powerUps) return;
                
                const equipment = {
                    x: Math.random() * 700 + 150,
                    y: Math.random() * 500 + 150,
                    width: 25,
                    height: 25,
                    type: 'equipment_drop',
                    collected: false,
                    effect: this.generateEquipmentEffect()
                };
                
                window.gameEngine.powerUps.push(equipment);
                this.currentRun.equipment++;
                
                console.log(`📦 装备掉落: ${equipment.effect.name}`);
                
            } catch (error) {
                console.error('装备掉落失败:', error);
            }
        }
        
        generateEquipmentEffect() {
            const effects = [
                { name: '伤害增强', type: 'damage', value: 1.3 },
                { name: '生命回复', type: 'heal', value: 50 },
                { name: '速度提升', type: 'speed', value: 1.2 },
                { name: '弹药补充', type: 'ammo', value: 30 },
                { name: '护盾', type: 'shield', value: 25 }
            ];
            
            return effects[Math.floor(Math.random() * effects.length)];
        }
        
        startGameMonitoring() {
            let lastLevel = 0;
            let lastGameState = '';
            
            setInterval(() => {
                try {
                    if (!this.active) return;
                    
                    const currentLevel = window.levelManager ? window.levelManager.currentLevel : 0;
                    const gameState = window.gameEngine ? window.gameEngine.gameState : '';
                    
                    // 关卡完成时自动应用升级
                    if (gameState === 'levelComplete' && lastGameState !== 'levelComplete') {
                        // 保存当前血量，以便下关继承
                        this.saveCurrentHealth();
                        
                        setTimeout(() => {
                            this.autoApplyUpgrade();
                        }, 1000);
                    }
                    
                    // 关卡开始时增强玩家
                    if (currentLevel > lastLevel && currentLevel > 0) {
                        this.enhancePlayerForLevel(currentLevel);
                        lastLevel = currentLevel;
                    }
                    
                    // 游戏结束时重置
                    if (gameState === 'gameOver' && lastGameState !== 'gameOver') {
                        this.resetRun();
                    }
                    
                    lastGameState = gameState;
                    
                } catch (error) {
                    // 静默处理错误
                }
            }, 1000);
        }
        
        autoApplyUpgrade() {
            try {
                const upgrades = [
                    () => this.applyDamageUpgrade(),
                    () => this.applyHealthUpgrade(),
                    () => this.applySpeedUpgrade(),
                    () => this.applyAmmoUpgrade()
                ];
                
                const randomUpgrade = upgrades[Math.floor(Math.random() * upgrades.length)];
                randomUpgrade();
                
                this.currentRun.upgrades.push(Date.now());
                console.log(`⚡ 自动应用升级 (总计: ${this.currentRun.upgrades.length})`);
                
            } catch (error) {
                console.error('升级应用失败:', error);
            }
        }
        
        applyDamageUpgrade() {
            try {
                if (window.player && window.player.currentWeapon && window.player.currentWeapon.damage) {
                    window.player.currentWeapon.damage = Math.floor(window.player.currentWeapon.damage * 1.25);
                }
            } catch (error) {}
        }
        
        applyHealthUpgrade() {
            try {
                if (window.player) {
                    window.player.maxHealth = Math.floor(window.player.maxHealth * 1.2);
                    window.player.health = window.player.maxHealth;
                    if (window.player.updateHealthUI) {
                        window.player.updateHealthUI();
                    }
                }
            } catch (error) {}
        }
        
        applySpeedUpgrade() {
            try {
                if (window.player && window.player.speed) {
                    window.player.speed *= 1.15;
                }
            } catch (error) {}
        }
        
        applyAmmoUpgrade() {
            try {
                if (window.player && window.player.currentWeapon) {
                    window.player.currentWeapon.totalAmmo += 50;
                    window.player.currentWeapon.ammo = Math.min(
                        window.player.currentWeapon.maxAmmo, 
                        window.player.currentWeapon.ammo + 20
                    );
                }
            } catch (error) {}
        }
        
        enhancePlayerForLevel(level) {
            try {
                if (!window.player) return;
                
                // 每关开始时小幅增强玩家
                const enhancement = 1 + (level * 0.02); // 每关2%增强
                
                if (window.player.currentWeapon && window.player.currentWeapon.damage) {
                    window.player.currentWeapon.damage = Math.floor(window.player.currentWeapon.damage * enhancement);
                }
                
                if (window.player.maxHealth) {
                    const healthBonus = Math.floor(level * 5);
                    window.player.maxHealth += healthBonus;
                    // 不自动加血，保持血量继承
                    if (window.player.updateHealthUI) {
                        window.player.updateHealthUI();
                    }
                }
                
                console.log(`🎯 关卡 ${level} 玩家增强完成`);
                
            } catch (error) {
                console.error('玩家增强失败:', error);
            }
        }
        
        startAttributeEnhancements() {
            // 定期微调游戏体验
            setInterval(() => {
                try {
                    if (!this.isGameActive()) return;
                    
                    this.applyMicroEnhancements();
                    this.trackKills();
                    this.manageResources();
                    
                } catch (error) {
                    // 静默处理
                }
            }, 5000);
        }
        
        applyMicroEnhancements() {
            try {
                if (!window.player) return;
                
                // 随机小幅提升（5%概率）
                if (Math.random() < 0.05) {
                    const enhancements = [
                        () => {
                            if (window.player.currentWeapon) {
                                window.player.currentWeapon.damage += 1;
                            }
                        },
                        () => {
                            if (window.player.health < window.player.maxHealth) {
                                window.player.health += 2;
                                if (window.player.updateHealthUI) {
                                    window.player.updateHealthUI();
                                }
                            }
                        },
                        () => {
                            if (window.player.currentWeapon && window.player.currentWeapon.totalAmmo < window.player.currentWeapon.maxAmmo) {
                                window.player.currentWeapon.totalAmmo += 5;
                            }
                        }
                    ];
                    
                    const enhancement = enhancements[Math.floor(Math.random() * enhancements.length)];
                    enhancement();
                }
                
            } catch (error) {}
        }
        
        trackKills() {
            try {
                if (window.storageManager) {
                    const data = window.storageManager.loadData();
                    const currentKills = data.player?.totalKills || 0;
                    
                    if (currentKills > this.lastKillCount) {
                        const newKills = currentKills - this.lastKillCount;
                        this.currentRun.kills += newKills;
                        this.lastKillCount = currentKills;
                        
                        // 每10个击杀给予奖励
                        if (this.currentRun.kills % 10 === 0) {
                            this.giveKillReward();
                        }
                    }
                }
            } catch (error) {}
        }
        
        giveKillReward() {
            try {
                const rewards = [
                    () => {
                        if (window.player && window.player.health < window.player.maxHealth) {
                            window.player.health += 10;
                            if (window.player.updateHealthUI) window.player.updateHealthUI();
                        }
                    },
                    () => {
                        if (window.player && window.player.currentWeapon) {
                            window.player.currentWeapon.totalAmmo += 15;
                        }
                    },
                    () => {
                        if (window.roguelikeSystem && window.roguelikeSystem.addCurrency) {
                            window.roguelikeSystem.addCurrency(5);
                        }
                    }
                ];
                
                const reward = rewards[Math.floor(Math.random() * rewards.length)];
                reward();
                
                console.log(`🏆 击杀奖励 (${this.currentRun.kills} 击杀)`);
                
            } catch (error) {}
        }
        
        manageResources() {
            try {
                if (!window.player) return;
                
                // 自动资源管理
                if (window.player.currentWeapon) {
                    // 弹药不足时自动补充
                    if (window.player.currentWeapon.ammo < 5 && window.player.currentWeapon.totalAmmo > 0) {
                        const reloadAmount = Math.min(
                            window.player.currentWeapon.maxAmmo - window.player.currentWeapon.ammo,
                            window.player.currentWeapon.totalAmmo
                        );
                        window.player.currentWeapon.ammo += reloadAmount;
                        window.player.currentWeapon.totalAmmo -= reloadAmount;
                    }
                }
                
                // 生命值低时有小概率自动回复
                if (window.player.health < window.player.maxHealth * 0.3 && Math.random() < 0.02) {
                    window.player.health += 5;
                    if (window.player.updateHealthUI) {
                        window.player.updateHealthUI();
                    }
                }
                
            } catch (error) {}
        }
        
        resetRun() {
            try {
                console.log(`💀 轮次结束 - 升级: ${this.currentRun.upgrades.length}, 装备: ${this.currentRun.equipment}, 击杀: ${this.currentRun.kills}`);
                
                // 保存统计到本地存储
                const stats = {
                    upgrades: this.currentRun.upgrades.length,
                    equipment: this.currentRun.equipment,
                    kills: this.currentRun.kills,
                    timestamp: Date.now()
                };
                
                const allRuns = JSON.parse(localStorage.getItem('roguelike_runs') || '[]');
                allRuns.push(stats);
                localStorage.setItem('roguelike_runs', JSON.stringify(allRuns));
                
                // 重置当前轮次
                this.currentRun = {
                    upgrades: [],
                    equipment: 0,
                    kills: 0
                };
                this.lastKillCount = 0;
                
            } catch (error) {
                console.error('轮次重置失败:', error);
            }
        }
        
        isGameActive() {
            try {
                return window.gameEngine && 
                       (window.gameEngine.gameState === 'playing' || 
                        window.gameEngine.gameState === 'levelComplete') &&
                       window.player && 
                       window.player.health > 0;
            } catch (error) {
                return false;
            }
        }
        
        // 血量继承系统
        startHealthPersistence() {
            if (!this.healthPersistence.enabled) return;
            
            this.healthPersistence.monitoring = true;
            console.log('🩸 血量继承系统已启用');
            
            // 监控血量变化
            setInterval(() => {
                this.monitorHealthChanges();
            }, 500);
        }
        
        monitorHealthChanges() {
            try {
                if (!window.player || !this.healthPersistence.monitoring) return;
                
                const currentHealth = window.player.health;
                const currentMaxHealth = window.player.maxHealth;
                
                // 检测到血量被重置为满血（且之前有保存的血量）
                if (this.healthPersistence.savedHealth !== null && 
                    currentHealth === currentMaxHealth && 
                    this.healthPersistence.savedHealth < currentMaxHealth) {
                    
                    // 恢复之前的血量
                    window.player.health = this.healthPersistence.savedHealth;
                    if (window.player.updateHealthUI) {
                        window.player.updateHealthUI();
                    }
                    
                    console.log(`🩸 血量已恢复: ${this.healthPersistence.savedHealth}/${currentMaxHealth}`);
                    
                    // 清除保存的血量，避免重复恢复
                    this.healthPersistence.savedHealth = null;
                }
                
                this.healthPersistence.lastMaxHealth = currentMaxHealth;
                
            } catch (error) {
                // 静默处理错误
            }
        }
        
        saveCurrentHealth() {
            try {
                if (window.player && this.healthPersistence.enabled) {
                    this.healthPersistence.savedHealth = window.player.health;
                    console.log(`🩸 保存当前血量: ${window.player.health}/${window.player.maxHealth}`);
                }
            } catch (error) {
                // 静默处理错误
            }
        }
        
        // 公共方法：获取统计
        getStats() {
            try {
                const allRuns = JSON.parse(localStorage.getItem('roguelike_runs') || '[]');
                return {
                    currentRun: this.currentRun,
                    totalRuns: allRuns.length,
                    bestRun: allRuns.reduce((best, run) => 
                        run.kills > (best.kills || 0) ? run : best, {}),
                    allRuns: allRuns
                };
            } catch (error) {
                return { currentRun: this.currentRun };
            }
        }
    }
    
    // 静默启动
    try {
        setTimeout(() => {
            const rogueEffects = new RoguelikeEffects();
            window.roguelikeEffects = rogueEffects;
            
            // 调试快捷键：Ctrl+Shift+R 查看统计
            window.addEventListener('keydown', (e) => {
                if (e.ctrlKey && e.shiftKey && e.code === 'KeyR') {
                    console.log('🎲 肉鸽统计:', rogueEffects.getStats());
                }
            });
            
        }, 1000);
        
    } catch (error) {
        console.error('肉鸽效果系统启动失败:', error);
    }
    
})();